<?php

namespace App\Observers;

use App\Jobs\TranslateSlug;
use App\Models\Article;
use App\Models\TagMap;
use Illuminate\Support\Facades\DB;

// creating, created, updating, updated, saving,
// saved,  deleting, deleted, restoring, restored

class ArticleObserver
{
    public function saving(Article $article)
    {
        //XSS过滤
        $article->body = clean($article->body, 'user_article_body');
        //生成话题摘录
        $article->excerpt = make_excerpt($article->body);

        if (is_array($article->tags)) {
            $article->tags = $article->tags[0];
        }
    }

    public function created(Article $article)
    {
        DB::table('categories')->where('id',$article->category_id)->increment('post_count');
        $this->dealAfterChange($article,'create');
    }
    public function deleted(Article $article)
    {
        $post_count = DB::table('categories')->where('id',$article->category_id)->pluck('post_count')->toArray()[0];
        if (($post_count-1)<0){
            $post_count=0;
        }else{
            $post_count -=1;
        }
        DB::table('categories')->where('id',$article->category_id)->update(['post_count'=>$post_count]);
        DB::table('replies')->where('article_id',$article->id)->delete();
        $this->dealAfterChange($article,'delete');
    }
    public function saved(Article $article)
    {
        // 如slug 字段无内容，使用翻译器对 title 进行翻译
        if (! $article->slug) {
            //推送任务到队列
            dispatch(new TranslateSlug($article));
        }
        $this->dealAfterChange($article,'update');
    }

    /**
     * @function 在新建和更新后处理标签数据
     * @param Article $article 文章实例
     * @param $option 数据库操作 create update
     */
    public function dealAfterChange(Article $article,$option)
    {
        //处理tags和中间表数据
        $aid = $article->id;
        $tagMap = new TagMap();
        $tids = explode(',',$article->tags);
        if (!empty($article->tags)){
            foreach ($tids as $k=>$tid) {
                $tagMaps[$k]['tid'] = $tid;
                $tagMaps[$k]['aid'] = $aid;
                //增加标签热度
                if ($option=='create')
                    DB::table('tags')->where('id',$tid)->increment('hot');
                elseif ($option=='delete')
                    break ;
            }
            //删除原标签
            $tagMap->delArticleTag($aid);
            //插入中间表数据
            if ($option=='delete'){
                return;
            }
            DB::table('tag_maps')->insert($tagMaps);
        }

    }
}